﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CdcSoftware.Pivotal.Applications.Core.Client;
using CdcSoftware.Pivotal.Applications.Core.Common;
using CdcSoftware.Pivotal.Engine;
using CdcSoftware.Pivotal.Engine.Client.Services.Interfaces;
using CdcSoftware.Pivotal.Engine.UI.Forms;
using CdcSoftware.Pivotal.Engine.Types.ServerTasks;

namespace Pcm.Inventory.Client.FormTasks
{
    public partial class RE_Inventory_Transfer : FormClientTask
    {
        bool allowProcessing = true;
        #region Goods Issue Form Events

        //DataTable deletedDT;

        /// <summary>
        /// This Event is fired on Change of Product Barcode  - Func - INV002
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.9.0     16/12/2011      VT          Initial version.
        /// </history>
        public virtual void OnUpdateProductBarcode(PivotalControl sender, EventArgs args)
        {
            try
            {
                int issuedQuantity = 0;
                bool productAdded = false;
                if (Convert.IsDBNull(this.PrimaryDataRow["Product_Barcode"]))
                    return;

                DataTable product = Globals.GetDataTable("RE_Product for Barcode? Alt Code1? Alt Code2? Alt Code3?",
                        new object[] { this.PrimaryDataRow["Product_Barcode"], this.PrimaryDataRow["Product_Barcode"], 
                        this.PrimaryDataRow["Product_Barcode"], this.PrimaryDataRow["Product_Barcode"]}, "Product_Id", "RE_Serialized", "RE_Product_Type");

                if(product != null && product.Rows.Count == 1)
                {
                    if (InventoryCheck(1, false, product.Rows[0]["Product_Id"], null))
                    {
                        //Check whether it is a serialized item or not.
                        if (TypeConvert.ToBoolean(product.Rows[0]["RE_Serialized"]))
                        {
                            this.PrimaryDataRow["Product_Id"] = product.Rows[0]["Product_Id"];
                            ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Product_Serial_No_Id")).ReadOnly = false;
                            ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Serial_Number")).ReadOnly = false;
                            this.FormControl.GetControlByDataName("RE_Serial_Number").Focus();
                            return;
                        }
                        else
                        {
                            //Non-Serialized Item. Add the product directly to the grid.
                            AddProductToGrid(product, null,null,false);
                            this.PrimaryDataRow["Product_Id"] = DBNull.Value;
                            productAdded = true;
                        }
                    }
                }
                else if (product != null && product.Rows.Count > 1)
                {
                    PivotalMessageBox.Show("Multiple Product's found for the keyed in/scanned barcode: " +
                        TypeConvert.ToString(this.PrimaryDataRow["Product_Barcode"]) + Environment.NewLine +
                        "Please contact the Administrator.", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                else
                {
                    PivotalMessageBox.Show("No Product record found for the keyed in/scanned barcode.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }

                this.PrimaryDataRow["RE_Serial_Number"] = DBNull.Value;
                this.PrimaryDataRow["RE_Product_Serial_No_Id"] = DBNull.Value;
                this.PrimaryDataRow["Product_Barcode"] = DBNull.Value;
                if (productAdded)
                {
                    DataTable transferProduct = this.FormData.DataSet.Tables[InventoryTransferProductSegment];
                    for (int i = 0; i < transferProduct.Rows.Count; i++)
                    {
                        if (transferProduct.Rows[i].RowState != DataRowState.Deleted && !TypeConvert.ToBoolean(transferProduct.Rows[i]["Marked_As_Delete"]))
                        {
                            if (TypeConvert.ToInt32(transferProduct.Rows[i][QuantityIssuedFieldName]) > 0)
                                issuedQuantity = issuedQuantity + TypeConvert.ToInt32(transferProduct.Rows[i][QuantityIssuedFieldName]);
                        }
                    }
                    this.PrimaryDataRow[TransferQuantityFieldName] = issuedQuantity;
                    this.FormControl.GetControlByName("ProductBarcode").Focus();
                }
                else
                {
                    this.FormControl.GetControlByDataName("Product_Id").Focus();
                }
                //if (Convert.IsDBNull(this.PrimaryDataRow[ProductBarcodeFieldName]))
                //    return;

                //DataTable productSKU = Globals.GetDataTable("RE Product SKU Barcode is ? LOB ?", new object[] { this.PrimaryDataRow[ProductBarcodeFieldName], 
                //    this.PrimaryDataRow["Line_Of_Business_Id"]}, ProductIdFieldName, REProductSKUIdFieldName, BarCodeFieldName);

                //if (productSKU != null && productSKU.Rows.Count == 1)
                //    FetchProductSKU(productSKU);
                //else if (productSKU != null && productSKU.Rows.Count > 1)
                //    PivotalMessageBox.Show("Multiple Product SKU's found for the keyed in/scanned barcode: " + TypeConvert.ToString(this.PrimaryDataRow[ProductBarcodeFieldName]) 
                //        + Environment.NewLine +"Please contact the Administrator", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //else
                //    PivotalMessageBox.Show("No Product SKU record found for the keyed in/scanned barcode.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                //this.PrimaryDataRow[ProductBarcodeFieldName] = DBNull.Value;
                //this.FormControl.GetControlByName("ProductBarcode").Focus();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On Key Down of Barcode field.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public virtual void BarCode_KeyPress(PivotalControl sender, KeyEventArgs  args)
       {
            try
            {
                if (args.KeyCode == Keys.Enter)
                {
                    this.FormControl.GetControlByDataName("Transfer_Quantity").Focus();//Don't worry abt the focus as it gets set again. This is just to naturally fire the datasourceupdated event.
                }
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
            //try
            //{
            //    if (args.KeyCode == Keys.Enter )
            //    {
            //        if (this.FormView.FormName == RENewGoodsReceiveTemp)
            //            this.FormControl.GetControlByName("ReceivedQuantity").Focus();
            //        else
            //            this.FormControl.GetControlByName("ScannerBatchNo").Focus();
            //    }                
            //}
            //catch (Exception ex)
            //{
            //    Globals.HandleException(ex, true);
            //}
        }

        /// <summary>
        /// Serial Number keyed in or populated after being scanned
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// <history>
        /// Revision   Date        Author  Description
        /// 6.0.12.0   04/03/2013  AS      Initial Version
        /// </history>
        public virtual void OnKeyDownSerialNumber(PivotalControl sender, KeyEventArgs args)
        {
            try
            {
                if (args.KeyCode == Keys.Enter)
                    this.FormControl.GetControlByDataName("Transfer_Quantity").Focus();
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
        }
        /// <summary>
        /// This Event is fired on Change of Product Id  - Func - INV003
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.9.0     16/12/2011      VT          Initial version.
        /// </history>
        public virtual void OnUpdateProduct(object sender, EventArgs args)
        {
            try
            {
                int issuedQuantity=0;
                bool productAdded = false;
                if (this.PrimaryDataRow["Product_Id"] != DBNull.Value)
                {
                    DataTable product = Globals.GetDataTable("Product", new List<NameValuePair>() { new NameValuePair("Product_Id", 
                        this.PrimaryDataRow["Product_Id"]) });
                    if (InventoryCheck(1, false, product.Rows[0]["Product_Id"], null))
                    {
                        //Check whether it is a serialized item or not.
                        if (!TypeConvert.ToBoolean(product.Rows[0]["RE_Serialized"]))
                        {
                            //Non-Serialized Item. Add the product directly to the grid.
                            AddProductToGrid(product, null,null,false);
                            productAdded = true;
                        }
                        else
                        {
                            ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Product_Serial_No_Id")).ReadOnly = false;
                            ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Serial_Number")).ReadOnly = false;
                            this.FormControl.GetControlByDataName("RE_Serial_Number").Focus();
                            return;
                        }
                    }
                }
                this.PrimaryDataRow["Product_Id"] = DBNull.Value;
                this.PrimaryDataRow["RE_Serial_Number"] = DBNull.Value;
                this.PrimaryDataRow["RE_Product_Serial_No_Id"] = DBNull.Value;
                ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Serial_Number")).ReadOnly = true;
                ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Product_Serial_No_Id")).ReadOnly = true;
                
                if (productAdded)
                {
                    DataTable transferProduct = this.FormData.DataSet.Tables[InventoryTransferProductSegment];
                    for (int i = 0; i < transferProduct.Rows.Count; i++)
                    {
                        if (transferProduct.Rows[i].RowState != DataRowState.Deleted && !TypeConvert.ToBoolean(transferProduct.Rows[i]["Marked_As_Delete"]))
                        {
                            if (TypeConvert.ToInt32(transferProduct.Rows[i][QuantityIssuedFieldName]) > 0)
                                issuedQuantity = issuedQuantity + TypeConvert.ToInt32(transferProduct.Rows[i][QuantityIssuedFieldName]);
                        }
                    }
                    this.PrimaryDataRow[TransferQuantityFieldName] = issuedQuantity;
                    this.PrimaryDataRow["Product_Id"] = DBNull.Value;
                    this.PrimaryDataRow["Product_Barcode"] = DBNull.Value;
                    this.FormControl.GetControlByName("ProductBarcode").Focus();
                }
                else
                {
                    this.FormControl.GetControlByDataName("Product_Id").Focus();
                }
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
            //try
            //{
            //    //this.PrimaryDataRow[ProductBarcodeFieldName] = DBNull.Value;
            //    //this.PrimaryDataRow[ProductSKUIdFieldName] = DBNull.Value;
            //    //if (Convert.IsDBNull(this.PrimaryDataRow[ProductIdFieldName]))
            //    //    ((PivotalForeignKey)this.FormControl.GetControlByDataName(ProductSKUIdFieldName)).ReadOnly = true;
            //    //else
            //    //    ((PivotalForeignKey)this.FormControl.GetControlByDataName(ProductSKUIdFieldName)).ReadOnly = false;               
            //    if (!Convert.IsDBNull(this.PrimaryDataRow[ProductIdFieldName]))
            //        ((PivotalForeignKey)this.FormControl.GetControlByDataName(ProductSKUIdFieldName)).ReadOnly = false;
            //    else
            //        ((PivotalForeignKey)this.FormControl.GetControlByDataName(ProductSKUIdFieldName)).ReadOnly = true;
            //}
            //catch (Exception ex)
            //{
            //    Globals.HandleException(ex, true);
            //}
        }

        /// <summary>
        /// This Event is fired on Change of Product SKU Id  - Func - INV004
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.9.0     16/12/2011      VT          Initial version.
        /// </history>
        public virtual void OnUpdateProductSKU(object sender, EventArgs args)
        {
            try
            {
                if (!Convert.IsDBNull(this.PrimaryDataRow[ProductSKUIdFieldName]))
                {
                    DataTable productSKU = Globals.GetDataTable("RE_Product_SKU", new List<NameValuePair>() { new NameValuePair("RE_Product_SKU_Id", 
                        Id.Create(this.PrimaryDataRow[ProductSKUIdFieldName])) });

                    if (productSKU != null && productSKU.Rows.Count == 1)
                    {
                        //Get the product details and populate the secondary.
                        FetchProductSKU(productSKU);
                        //Reset the product and sku fields.
                        this.PrimaryDataRow[ProductIdFieldName] = DBNull.Value;
                        this.PrimaryDataRow[ProductSKUIdFieldName] = DBNull.Value;
                    }

                    //Set the Product SKU field to read-only again
                    if (this.PrimaryDataRow[ProductIdFieldName] != DBNull.Value)
                        ((PivotalForeignKey)this.FormControl.GetControlByName("ProductSKUId")).ReadOnly = false;
                    else
                        ((PivotalForeignKey)this.FormControl.GetControlByName("ProductSKUId")).ReadOnly = true;
                    this.FormControl.GetControlByDataName(ProductIdFieldName).Focus();
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Add the Product SKU to the Grid.
        /// </summary>
        private void FetchProductSKU(DataTable productSKU)
        {
            //DS:30102012 - Added Product Type check for not allowing Misc. Income type as per CR-VII.
            object productType = Pcm.Retail.Client.Globals.ServerSqlIndex(ProductTableName, REProductTypeFieldName, Id.Create(productSKU.Rows[0][ProductIdFieldName]));
            if (string.Equals(TypeConvert.ToString(productType), "Miscellaneous Income"))
            {
                //Miscellaneous Income can not be added explicitly.
                PivotalMessageBox.Show("Miscellaneous Income can't be added explicitly.", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            else
            {
                if (ValidateInventory(productSKU.Rows[0][REProductSKUIdFieldName], this.PrimaryDataRow[FromStorageLocationIdFieldName]))
                {
                    //Create Transfer Product secondary
                    DataTable transferProducts = this.FormData.DataSet.Tables[InventoryTransferProductSegment];
                    base.NewSecondaryRecord(InventoryTransferProductSegment);
                    DataRow transferProduct = transferProducts.Rows[transferProducts.Rows.Count - 1];
                    transferProduct[QuantityIssuedFieldName] = 1;
                    transferProduct[QuantityReceivedFieldName] = 0;
                    transferProduct[QuantityOpenFieldName] = -1;
                    transferProduct[ProductIdFieldName] = productSKU.Rows[0][ProductIdFieldName];
                    transferProduct[ProductSKUIdFieldName] = productSKU.Rows[0][REProductSKUIdFieldName];
                    transferProduct[ReceivedFieldName] = false;
                    transferProduct[FromStorageLocationIdFieldName] = PrimaryDataRow[FromStorageLocationIdFieldName];
                    transferProduct[ToStorageLocationIdFieldName] = PrimaryDataRow[ToStorageLocationIdFieldName];
                    transferProduct[ProductBarcodeFieldName] = productSKU.Rows[0][BarCodeFieldName];
                    //DS:16102012 - Set the "Marked_As_Delete" field value to false.
                    transferProduct[MarkedAsDeleteFieldName] = false;
                }
                this.PrimaryDataRow["Transfer_Quantity"] = TypeConvert.ToInt32(this.PrimaryDataRow["Transfer_Quantity"]) + 1;
                //NN 30 March 2012:Issue 79:
                //Commenting below function call sinc,color highlighting is required only got Goods Receive form
                //this.HighlightRows();
            }
        }

        /// <summary>
        /// This Event is fired on Change of Status Id  - Func - INV005
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.9.0     16/12/2011      VT          Initial version.
        /// </history>
        public virtual void OnUpdateStatus(object sender, EventArgs args)
        {
            try
            {
                if (this.PrimaryDataRow[Status.FieldName] == DBNull.Value)
                    return;
                
                string currentStatusValue = TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]);
                DataTable transferProduct = this.FormData.DataSet.Tables[InventoryTransferProductSegment];
                //New, Hold, Issued, Cancel
                if (this.RecordId == null)
                {
                    if (currentStatusValue != Status.New && currentStatusValue != Status.Hold &&
                        currentStatusValue != Status.Issued)
                    {
                        PivotalMessageBox.Show("You can set your status as 'New' Or 'Hold' Or 'Issued'", MessageBoxButtons.OK,MessageBoxIcon.Information);
                        this.PrimaryDataRow[Status.FieldName] = Status.New;
                        return;
                    }
                }

                if (this.RecordId != null)
                {
                    if (this.PrimaryDataRow[Status.FieldName] == this.PrimaryDataRow[Status.FieldName, DataRowVersion.Original])
                        return;
                    string origStatusValue = TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName, DataRowVersion.Original]);
                    if ((origStatusValue == Status.New) && (currentStatusValue != Status.Hold &&
                                                        currentStatusValue != Status.Cancel &&
                                                        currentStatusValue != Status.Issued))
                    {
                        PivotalMessageBox.Show("You can set your status only to 'Hold' Or 'Issued' Or 'Cancel'", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.PrimaryDataRow[Status.FieldName] = this.PrimaryDataRow[Status.FieldName, DataRowVersion.Original];
                        return;
                    }
                    if ((origStatusValue == Status.Hold) && (currentStatusValue != Status.Cancel &&
                                                        currentStatusValue != Status.Issued))
                    {
                        PivotalMessageBox.Show("You can set your status only to 'Issued' Or 'Cancel'", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.PrimaryDataRow[Status.FieldName] = this.PrimaryDataRow[Status.FieldName, DataRowVersion.Original];
                        return;
                    }
                    if ((origStatusValue == Status.Issued) && (currentStatusValue != Status.Cancel))
                    {
                        PivotalMessageBox.Show("Cannot set the status to " + TypeConvert.ToString(currentStatusValue), MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.PrimaryDataRow[Status.FieldName] = this.PrimaryDataRow[Status.FieldName, DataRowVersion.Original];
                        this.FormView.Dirty = false;
                        return;
                    }

                    //DS:31102012 - Added the check for inventory product items to be received. When all the items are received, it is not required to ask the user for confirmation.
                    bool setReceiveStatus = true;

                    //if (transferProduct != null && transferProduct.Rows.Count > 0)
                    //{
                    //    for (int i = 0; i < transferProduct.Rows.Count; i++)
                    //    {
                    //        if (transferProduct.Rows[i].RowState != DataRowState.Deleted && !TypeConvert.ToBoolean(transferProduct.Rows[i]["Marked_As_Delete"]))
                    //        {
                    //            if (!TypeConvert.ToBoolean(transferProduct.Rows[i]["Received"]))
                    //                setReceiveStatus = false;
                    //        }
                    //    }
                    //}
                    //if (!setReceiveStatus)
                    //{
                    //    if (PivotalMessageBox.Show("Do you want to change the status from " + TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName, DataRowVersion.Original]) +
                    //                                " To " + TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) + " ?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    //    {
                    //        this.PrimaryDataRow[Status.FieldName] = this.PrimaryDataRow[Status.FieldName, DataRowVersion.Original];
                    //        return;
                    //    }
                    //}
                }

                #region Issued Status event

                if (currentStatusValue == Status.Issued)
                {
                    if (transferProduct == null || transferProduct.Rows.Count == 0)
                    {
                        PivotalMessageBox.Show("This record can be issued only if it has transfer products.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        if (this.RecordId != null)
                            this.PrimaryDataRow[Status.FieldName] = this.PrimaryDataRow[Status.FieldName, DataRowVersion.Original];
                        else
                            this.PrimaryDataRow[Status.FieldName] = Status.New;
                        return;
                    }
                }

                #endregion

                //Enable or disable Buttons based on status
                this.EnableDisableButtons();

                #region INV016 when status is Received
                if (TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) == Status.Received)
                {
                    this.EnableDisableAllFields(false);
                    return;
                }

                #endregion

                //NN 22 Aug 2012:Added code to set CancelDate id Status is set to cancel
                #region when status is Cancel
                if (TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) == Status.Cancel)
                {
                    if (this.FormView.FormName.Equals("RE_Goods_Issue"))
                    {
                        if (this.RecordId != null)
                        {
                            if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName, DataRowVersion.Original]), Status.Issued))
                            {
                                if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "Inventory Transfer"))
                                {
                                    PivotalMessageBox.Show("Cannot set the status to cancel", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    this.PrimaryDataRow[Status.FieldName] = this.PrimaryDataRow[Status.FieldName, DataRowVersion.Original];
                                    this.FormView.Dirty = false;
                                    return;
                                }
                            }
                        }
                        else
                        {
                            PivotalMessageBox.Show("You can set your status as 'New' Or 'Hold' Or 'Issued'", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            this.PrimaryDataRow[Status.FieldName] = Status.New;
                            return;
                        }
                    }
                    this.PrimaryDataRow["Cancel_date"] = DateTime.Now;                    
                }
                #endregion
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc, true);
            }
        }

        /// <summary>
        /// Invoked when 'Print Goods Issue' Button is clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public virtual void OnPrintGoodsIssueBtnClick(object sender, EventArgs args)
        {
            try
            {
                string errMsg = string.Empty;
                if (this.FormView.Dirty || this.RecordId == null || this.FormView.ValidateRequiredFields(out errMsg) == false)
                {
                    if (this.FormView.SaveRecord() == false)
                    {
                        return;
                    }
                }
                Globals.ShowReport("RE_Print Goods Issue", RecordFilter.IndividualRecord, this.RecordId, null);
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Create New GI Button Click 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public virtual void OnCreateNewGIBtnClick(object sender, EventArgs args)
        {
            try
            {
                #region INV008

                if (this.FormView == null)
                    return;

                string errMsg = string.Empty;

                if (this.FormView.Dirty || this.RecordId == null || this.FormView.ValidateRequiredFields(out errMsg) == false)
                {
                    if (this.FormView.SaveRecord() == false)
                    {
                        return;
                    }
                }
                bool hasTransferProducts = false;
                DataTable invTransferProducts = Globals.GetDataTable(PendingInvTransferProductforTransferIdQueryName, new object[] { this.RecordId.ToByteArray() },
                                             new string[] { ProductBarcodeFieldName, ProductIdFieldName, QuantityOpenFieldName, FromStorageLocationIdFieldName });
                if (invTransferProducts != null && invTransferProducts.Rows.Count > 0)
                {
                    hasTransferProducts = true;

                    Id[] itemsList = Globals.ShowMultipleSelectionList(invTransferProducts, "Pending Items", "");
                    if (itemsList.Length > 0)
                    {
                        int length = itemsList.Length;
                        object[] objectArr = new object[] { };
                        objectArr = new object[length];
                        for (int i = 0; i < itemsList.Length; i++)
                        {
                            objectArr[i] = TypeConvert.ToDBValue((Id)itemsList.GetValue(i));
                        }
                        //Set default columns for the primary fields
                        this.TransitionPointParameter.AddDefaultColumn(Status.FieldName, Status.New);

                        if (this.PrimaryDataRow[FromStorageLocationIdFieldName] != DBNull.Value)
                        {
                            this.TransitionPointParameter.AddDefaultColumn(FromStorageLocationIdFieldName, this.PrimaryDataRow[FromStorageLocationIdFieldName]);
                        }
                        if (this.PrimaryDataRow[FromStaffIdFieldName] != DBNull.Value)
                        {
                            this.TransitionPointParameter.AddDefaultColumn(FromStaffIdFieldName, this.PrimaryDataRow[FromStaffIdFieldName]);
                        }
                        this.TransitionPointParameter.AddDefaultColumn(IssueDateFieldName, DateTime.Now);
                        if (this.PrimaryDataRow[ToStorageLocationIdFieldName] != DBNull.Value)
                        {
                            this.TransitionPointParameter.AddDefaultColumn(ToStorageLocationIdFieldName, this.PrimaryDataRow[ToStorageLocationIdFieldName]);
                        }
                        if (this.PrimaryDataRow[TransferQuantityFieldName] != DBNull.Value)
                        {
                            this.TransitionPointParameter.AddDefaultColumn(TransferQuantityFieldName, this.PrimaryDataRow[TransferQuantityFieldName]);
                        }

                        this.TransitionPointParameter.AddDefaultColumn("Remarks_1", "Copied from Goods - Issue - " + TypeConvert.ToString(this.PrimaryDataRow["Transfer_Id"]));
                        this.TransitionPointParameter.AddDefaultColumn("DisconnStore_Value", this.PrimaryDataRow["DisconnStore_Value"]);

                        this.TransitionPointParameter.SetUserDefinedParameter(1, "CreateNewGIWithPendingItems");
                        this.TransitionPointParameter.SetUserDefinedParameter(2, objectArr);
                        this.TransitionPointParameter.SetUserDefinedParameter(3, this.RecordId.ToByteArray());
                        ParameterList pList = this.TransitionPointParameter.Construct();

                        //Show the new Goods Issue form with only the Pending Items //DisconnOrig_Goods_Issue_Id
                        Globals.ShowForm(REGoodsIssueClientForm, null, pList);
                        return;
                    }
                }
                if (hasTransferProducts == false)
                {
                    PivotalMessageBox.Show("You need to have records in Items for this On Create New GI button to work.", MessageBoxButtons.OK,MessageBoxIcon.Information);
                    return;
                }

                #endregion
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Remove Items Button Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public virtual void OnRemoveItemsBtnClick(object sender, EventArgs args)
        {
            try
            {
                #region INV009

                if (this.FormView == null)
                    return;

                string errMsg = string.Empty;

                if (this.FormView.Dirty || this.RecordId == null || this.FormView.ValidateRequiredFields(out errMsg) == false)
                {
                    if (!this.FormView.SaveRecord())
                        return;
                }
                bool hasTransferProducts = false;
                DataTable invTransferProducts = Globals.GetDataTable(PendingInvTransferProductforTransferIdQueryName, new object[] { this.RecordId.ToByteArray() },
                                             new string[] { ProductBarcodeFieldName  });
                if (invTransferProducts != null && invTransferProducts.Rows.Count > 0)
                    hasTransferProducts = true;

                if (!hasTransferProducts)
                {
                    PivotalMessageBox.Show("There are no pending transfer items to remove.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                Id[] itemsList = Globals.ShowMultipleSelectionList(invTransferProducts, "Pending Transfer Items", "");
                if (itemsList.Length > 0)
                {
                    string productIdArray = string.Empty;
                    for (int i = 0; i < itemsList.Length; i++)
                    {
                        if (string.IsNullOrEmpty(productIdArray))
                            productIdArray = Id.Create(itemsList.GetValue(i)).ToString();
                        else
                            productIdArray = productIdArray + "," + Id.Create(itemsList.GetValue(i)).ToString();
                    }

                    this.SystemClient.ExecuteServerTask("RE_Inventory_Transfer", "RemovePendingItems", new Type[] { typeof(object), typeof(string) },
                        new object[] { this.RecordId.ToByteArray(), productIdArray });
                    this.FormView.LoadRecord();
                }
                #endregion
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Create Copy Button Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public virtual void OnCreateCopyBtnClick(object sender, EventArgs args)
        {
            try
            {
                #region INV010

                if (this.FormView == null)
                    return;

                string errMsg = string.Empty;

                if (this.FormView.Dirty || this.RecordId == null || this.FormView.ValidateRequiredFields(out errMsg) == false)
                {
                    if (this.FormView.SaveRecord() == false)
                    {
                        return;
                    }
                }
                //Set default columns for the primary fields
                this.TransitionPointParameter.AddDefaultColumn(Status.FieldName, Status.New);
                if (this.PrimaryDataRow[FromStorageLocationIdFieldName] != DBNull.Value)
                {
                    this.TransitionPointParameter.AddDefaultColumn(FromStorageLocationIdFieldName, this.PrimaryDataRow[FromStorageLocationIdFieldName]);
                }
                if (this.PrimaryDataRow[FromStaffIdFieldName] != DBNull.Value)
                {
                    this.TransitionPointParameter.AddDefaultColumn(FromStaffIdFieldName, this.PrimaryDataRow[FromStaffIdFieldName]);
                }
                this.TransitionPointParameter.AddDefaultColumn(IssueDateFieldName, DateTime.Now);
                if (this.PrimaryDataRow[ToStorageLocationIdFieldName] != DBNull.Value)
                {
                    this.TransitionPointParameter.AddDefaultColumn(ToStorageLocationIdFieldName, this.PrimaryDataRow[ToStorageLocationIdFieldName]);
                }
                if (this.PrimaryDataRow[TransferQuantityFieldName] != DBNull.Value)
                {
                    this.TransitionPointParameter.AddDefaultColumn(TransferQuantityFieldName, this.PrimaryDataRow[TransferQuantityFieldName]);
                }
                this.TransitionPointParameter.AddDefaultColumn("Remarks_1", "Copied from Goods - Issue - " + TypeConvert.ToString(this.PrimaryDataRow["Transfer_Id"]));
                this.TransitionPointParameter.AddDefaultColumn("DisconnStore_Value", this.PrimaryDataRow["DisconnStore_Value"]);

                this.TransitionPointParameter.SetUserDefinedParameter(1, "CreateCopyGoodsIssue");
                this.TransitionPointParameter.SetUserDefinedParameter(2, null);
                this.TransitionPointParameter.SetUserDefinedParameter(3, this.RecordId.ToByteArray());
                ParameterList pList = this.TransitionPointParameter.Construct();
                //Show the new Goods Issue form with all the Transfer products
                Globals.ShowForm(REGoodsIssueClientForm, null, pList);
                return;

                #endregion
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On Update Store field.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public virtual void OnUpdateToStore(object sender, EventArgs args)
        {
            try
            {
                if (this.PrimaryDataRow[ToStorageLocationIdFieldName] != DBNull.Value)
                {
                    if (!Convert.IsDBNull(this.PrimaryDataRow[FromStorageLocationIdFieldName]))
                    {
                        object fromStoreLOB = Globals.SqlIndex("RE_Storage_Location", "LOB_Id", Id.Create(this.PrimaryDataRow[FromStorageLocationIdFieldName]));
                        object toStoreLOB = Globals.SqlIndex("RE_Storage_Location", "LOB_Id", Id.Create(this.PrimaryDataRow[ToStorageLocationIdFieldName]));
                        if (!Id.Equals(Id.Create(fromStoreLOB), Id.Create(toStoreLOB)))
                        {
                            PivotalMessageBox.Show("To Store should belong to the same LOB as From Store.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            this.PrimaryDataRow[ToStorageLocationIdFieldName] = DBNull.Value;
                            return;
                        }
                    }
                    foreach (DataRow dr in this.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"].Rows)
                    {
                        dr[ToStorageLocationIdFieldName] = this.PrimaryDataRow[ToStorageLocationIdFieldName];
                    }
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On Update Store field.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public virtual void OnUpdateFromStore(object sender, EventArgs args)
        {
            try
            {
                if (this.PrimaryDataRow[FromStorageLocationIdFieldName] != DBNull.Value)
                {
                    if (!Convert.IsDBNull(this.PrimaryDataRow[ToStorageLocationIdFieldName]))
                    {
                        object fromStoreLOB = Globals.SqlIndex("RE_Storage_Location", "LOB_Id", Id.Create(this.PrimaryDataRow[FromStorageLocationIdFieldName]));
                        object toStoreLOB = Globals.SqlIndex("RE_Storage_Location", "LOB_Id", Id.Create(this.PrimaryDataRow[ToStorageLocationIdFieldName]));
                        if (!Id.Equals(Id.Create(fromStoreLOB), Id.Create(toStoreLOB)))
                        {
                            PivotalMessageBox.Show("From Store should belong to the same LOB as To Store.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            this.PrimaryDataRow[FromStorageLocationIdFieldName] = DBNull.Value;
                            return;
                        }                        
                    }
                    foreach (DataRow dr in this.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"].Rows)
                    {
                        dr[FromStorageLocationIdFieldName] = this.PrimaryDataRow[FromStorageLocationIdFieldName];
                    }
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Issue No 77
        /// On delete of Secondary row
        /// Method implemented to update Transfer_Quantity of this record if secondary is deleted.
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="args">EventArgs</param>
        /// <history>
        /// Revision   Date        Author  Description
        /// 6.0.10.1    27/03/2012  NN      Initial Version
        /// </history>
        public virtual void OnSecondaryDeleteClick(PivotalControl sender, EventArgs args)
        {
            try
            {
                DataGridViewCellCancelEventArgs cancelargs = (DataGridViewCellCancelEventArgs)args;
                int rowIndex = cancelargs.RowIndex;
                IEnumerable<DataRow> query = null;
                DataTable transferProduct = this.FormData.DataSet.Tables[InventoryTransferProductSegment];
                DataTable transferReceiveProduct = this.FormData.DataSet.Tables["RE_Inv_Trnsf_Rec_Batch_Invento"];

                if (this.FormView.FormName == "RE_Goods_Receive")
                {
                    if (transferProduct != null && transferProduct.Rows.Count > 0)
                    {
                        if (Convert.IsDBNull(transferReceiveProduct.Rows[rowIndex]["Product_Serial_No_Id"]))
                        {
                            query = from prods in transferProduct.AsEnumerable()
                                    where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(transferReceiveProduct.Rows[rowIndex]["Product_Id"])
                                    select prods;
                        }
                        else
                        {
                            query = from prods in transferProduct.AsEnumerable()
                                    where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(transferReceiveProduct.Rows[rowIndex]["Product_Id"])
                                    && Id.Create(prods.Field<byte[]>("RE_Product_Serial_No_Id")) == Id.Create(transferReceiveProduct.Rows[rowIndex]["Product_Serial_No_Id"])
                                    select prods;
                        }

                        if (query != null && query.Count() > 0)
                        {
                            List<DataRow> test = query.ToList();
                            test[0]["Quantity_Received"] = TypeConvert.ToInt32(test[0]["Quantity_Received"]) - 1;
                            test[0]["Received"] = false;
                            this.PrimaryDataRow["Received_Quantity_PerBatch"] = TypeConvert.ToInt32(this.PrimaryDataRow["Received_Quantity_PerBatch"]) - 1;
                            if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "PO Receive") ||
                                        String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "Inventory Receive"))
                            {
                                this.PrimaryDataRow["Received_Quantity"] = TypeConvert.ToInt32(this.PrimaryDataRow["Received_Quantity"]) - 1;
                            }
                        }
                    }
                    transferReceiveProduct.Rows.Remove(transferReceiveProduct.Rows[rowIndex]);
                    cancelargs.Cancel = true;
                }
                if (this.FormView.FormName == "RE_RMA")
                {
                    if (this.RecordId != null)
                    {
                        if (transferProduct != null && transferProduct.Rows.Count > 0)
                        {
                            PivotalMessageBox.Show("The Line Item cannot be deleted", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        cancelargs.Cancel = true;
                    }
                }

            }
            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
        }

        /// <summary>
        /// On change of Product Serial Number field 
        /// </summary>
        /// <param name="sender">PivotalControl</param>
        /// <param name="args">EventArgs</param>
        /// <history>
        /// Revision   Date        Author  Description
        /// 6.0.12.0   28/01/2013  DS      Initial Version
        /// </history>
        public virtual void OnDataSourceUpdatedSerialNumberText(PivotalControl sender, EventArgs args)
        {
            try
            {
                int issuedQuantity = 0;
                bool productAdded = false;
                if (!Convert.IsDBNull(this.PrimaryDataRow["RE_Serial_Number"]) && !Convert.IsDBNull(this.PrimaryDataRow["Product_Id"]))
                {
                    //Check for Inventory. No Inventory, do not allow to add products. 
                    DataTable inventory = Globals.GetDataTable("RE_Inventory for StorageLocation? Product?",
                        new object[] { this.PrimaryDataRow["From_Storage_Location_Id"], this.PrimaryDataRow["Product_Id"] }, "Product_Id", "Quantity_Actual");

                    if (inventory != null && inventory.Rows.Count > 0 && TypeConvert.ToInt16(inventory.Rows[0]["Quantity_Actual"]) >= 1)
                    {
                        DataTable productSerialNo = Globals.GetDataTable("RE_Product Serial No for Product? Serial_Number? Storage Location?",
                            new object[] { this.PrimaryDataRow["Product_Id"], this.PrimaryDataRow["RE_Serial_Number"], this.PrimaryDataRow["From_Storage_Location_Id"] },
                            "RE_Product_Serial_No_Id", "Serial_Number", "Product_Id", "Available_For_Sale", "Voucher", "Voucher_Status");

                        if (productSerialNo != null && productSerialNo.Rows.Count > 0)
                        {
                            AddProductToGrid(null, productSerialNo, null, false);
                            this.PrimaryDataRow["Product_Id"] = DBNull.Value;
                            productAdded = true;
                        }
                        else
                        {
                            PivotalMessageBox.Show("No prouct found for the keyed in/scanned Serial Number.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                    }
                    else
                    {
                        PivotalMessageBox.Show("No stock found for the keyed in/scanned barcode.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }

                    this.PrimaryDataRow["RE_Serial_Number"] = DBNull.Value;
                    if (productAdded)
                    {
                        DataTable transferProduct = this.FormData.DataSet.Tables[InventoryTransferProductSegment];
                        for (int i = 0; i < transferProduct.Rows.Count; i++)
                        {
                            if (transferProduct.Rows[i].RowState != DataRowState.Deleted && !TypeConvert.ToBoolean(transferProduct.Rows[i]["Marked_As_Delete"]))
                            {
                                if (TypeConvert.ToInt32(transferProduct.Rows[i][QuantityIssuedFieldName]) > 0)
                                    issuedQuantity = issuedQuantity + TypeConvert.ToInt32(transferProduct.Rows[i][QuantityIssuedFieldName]);
                            }
                        }
                        this.PrimaryDataRow[TransferQuantityFieldName] = issuedQuantity;
                        this.PrimaryDataRow["Product_Barcode"] = DBNull.Value;
                        ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Serial_Number")).ReadOnly = true;
                        ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Product_Serial_No_Id")).ReadOnly = true;
                        this.FormControl.GetControlByDataName("Product_Barcode").Focus();
                    }
                    else
                    {
                        this.FormControl.GetControlByDataName("RE_Serial_Number").Focus();
                    }
                }
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
        }

        /// <summary>
        /// On change of Product Serial Number dropdown field 
        /// </summary>
        /// <param name="sender">PivotalControl</param>
        /// <param name="args">EventArgs</param>
        /// <history>
        /// Revision   Date        Author  Description
        /// 6.0.12.0   28/01/2013  DS      Initial Version
        /// </history>
        public virtual void OnDataSourceUpdatedSerialNumberDropDown(PivotalControl sender, EventArgs args)
        {
            try
            {
                int issuedQuantity = 0;
                bool productAdded = false;
                if (!Convert.IsDBNull(this.PrimaryDataRow["RE_Product_Serial_No_Id"]) && !Convert.IsDBNull(this.PrimaryDataRow["Product_Id"]))
                {   
                    DataTable inventory = Globals.GetDataTable("RE_Inventory for StorageLocation? Product?",
                        new object[] { this.PrimaryDataRow["From_Storage_Location_Id"], this.PrimaryDataRow["Product_Id"] }, "Product_Id", "Quantity_Actual");

                    if (inventory != null && inventory.Rows.Count > 0 && TypeConvert.ToInt16(inventory.Rows[0]["Quantity_Actual"]) >= 1)
                    {
                        DataTable productSerialNo = Globals.GetDataTable("RE_Product Serial No for Product? Serial_Number? Storage Location?",
                                new object[] { this.PrimaryDataRow["Product_Id"], this.PrimaryDataRow["RE_Product_Serial_No_Id_Serial"], this.PrimaryDataRow["From_Storage_Location_Id"] },
                                "RE_Product_Serial_No_Id", "Serial_Number", "Product_Id", "Available_For_Sale", "Voucher", "Voucher_Status");

                        if (productSerialNo != null && productSerialNo.Rows.Count > 0)
                        {
                            AddProductToGrid(null, productSerialNo, null, false);
                            this.PrimaryDataRow["Product_Id"] = DBNull.Value;
                            productAdded = true;
                        }
                        else
                        {
                            PivotalMessageBox.Show("No product found for the selected Serial Number.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                    }
                    this.PrimaryDataRow["RE_Serial_Number"] = DBNull.Value;
                    this.PrimaryDataRow["RE_Product_Serial_No_Id"] = DBNull.Value;

                    if (productAdded)
                    {
                        DataTable transferProduct = this.FormData.DataSet.Tables[InventoryTransferProductSegment];
                        for (int i = 0; i < transferProduct.Rows.Count; i++)
                        {
                            if (transferProduct.Rows[i].RowState != DataRowState.Deleted && !TypeConvert.ToBoolean(transferProduct.Rows[i]["Marked_As_Delete"]))
                            {
                                if (TypeConvert.ToInt32(transferProduct.Rows[i][QuantityIssuedFieldName]) > 0)
                                    issuedQuantity = issuedQuantity + TypeConvert.ToInt32(transferProduct.Rows[i][QuantityIssuedFieldName]);
                            }
                        }
                        this.PrimaryDataRow[TransferQuantityFieldName] = issuedQuantity;
                        this.PrimaryDataRow["Product_Barcode"] = DBNull.Value;
                        ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Serial_Number")).ReadOnly = true;
                        ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Product_Serial_No_Id")).ReadOnly = true;
                        this.FormControl.GetControlByName("ProductBarcode").Focus();
                    }
                    else
                    {
                        this.FormControl.GetControlByDataName("RE_Product_Serial_No_Id").Focus();
                    }
                }
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
        }

        #endregion

        #region Goods Receive Form Events

        /// <summary>
        /// This Event is fired on Change of Product Barcode  - Func - INV013
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.9.0     29/12/2011      VT          Initial version.
        /// </history>
        public virtual void OnUpdateReceiveProductBarcode(object sender, EventArgs args)
        {
            try
            {
                bool productAdded = false;
                DataTable transferProducts = this.FormData.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"];
                DataTable transferProductsRecBatch = this.FormData.DataSet.Tables["RE_Inv_Trnsf_Rec_Batch_Invento"];
                if (this.PrimaryDataRow[ProductBarcodeFieldName] == DBNull.Value)
                    return;
                this.PrimaryDataRow["Product_Id"] = DBNull.Value;
                DataTable product = Globals.GetDataTable("RE_Product for Barcode? Alt Code1? Alt Code2? Alt Code3?",
                        new object[] { this.PrimaryDataRow["Product_Barcode"], this.PrimaryDataRow["Product_Barcode"], 
                        this.PrimaryDataRow["Product_Barcode"], this.PrimaryDataRow["Product_Barcode"]}, "Product_Id", "RE_Serialized", "RE_Product_Type");

                if (product != null && product.Rows.Count == 1)
                {
                    if (TypeConvert.ToBoolean(product.Rows[0]["RE_Serialized"]))
                    {
                        this.PrimaryDataRow["Product_Id"] = product.Rows[0]["Product_Id"];
                        ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Product_Serial_No_Id")).ReadOnly = false;
                        ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Serial_Number")).ReadOnly = false;
                        this.FormControl.GetControlByDataName("RE_Serial_Number").Focus();
                        return;
                    }
                    else
                    {
                        if (transferProductsRecBatch != null && transferProductsRecBatch.Rows.Count > 0)
                        {
                            IEnumerable<DataRow> query = from prods in transferProducts.AsEnumerable()
                                                         where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(product.Rows[0]["Product_Id"])
                                                             //&& Id.Create(prods.Field<byte[]>("RE_Product_Serial_No_Id")) == null
                                                         && prods.Field<bool>("Received") == false
                                                         select prods;
                            if (query != null && query.Count() == 0)
                            {

                                List<Int32?> issueQty = (from var in transferProducts.AsEnumerable()
                                                         where Id.Create(var.Field<byte[]>("Product_Id")) == Id.Create(product.Rows[0]["Product_Id"])
                                                         select var.Field<Int32?>("Quantity_Issued")).ToList();

                                List<Int32?> receivedQty = (from var in transferProducts.AsEnumerable()
                                                            where Id.Create(var.Field<byte[]>("Product_Id")) == Id.Create(product.Rows[0]["Product_Id"])
                                                            select var.Field<Int32?>("Quantity_Received")).ToList();

                                if (issueQty.Count() != 0 && issueQty.Count != 0)
                                {
                                    if (TypeConvert.ToInt32(issueQty[0]) == TypeConvert.ToInt32(receivedQty[0]))
                                    {
                                        PivotalMessageBox.Show("Item has been fully received.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        this.PrimaryDataRow["Product_Barcode"] = DBNull.Value;
                                        this.FormControl.GetControlByDataName("Product_Barcode").Focus();
                                        return;
                                    }
                                }
                                //int totalQty = transferProductsRecBatch.AsEnumerable().Where(a => (Id.Create(a["Product_Id"])
                                //    == Id.Create(product.Rows[0]["Product_Id"]) && TypeConvert.ToInt32(a["Quantity"]) > 0)).Sum(a => TypeConvert.ToInt32(a["Qty"]));
                            }
                        }
                        else
                        {
                            DataTable transferprodRecBatch = Globals.GetDataTable("RE Inv Transfer Rec Batch for InvTransfer Id?", new object[] { this.RecordId }
                                , new string[] { "RE_Inv_Trnsf_Rec_Batch_Id" });
                            if (transferprodRecBatch != null && transferprodRecBatch.Rows.Count > 0)
                            {
                                IEnumerable<DataRow> query = from prods in transferProducts.AsEnumerable()
                                                             where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(product.Rows[0]["Product_Id"])
                                                                 //&& Id.Create(prods.Field<byte[]>("RE_Product_Serial_No_Id")) == null
                                                             && prods.Field<bool>("Received") == false
                                                             select prods;
                                if (query != null && query.Count() == 0)
                                {

                                    List<Int32?> issueQty = (from var in transferProducts.AsEnumerable()
                                                             where Id.Create(var.Field<byte[]>("Product_Id")) == Id.Create(product.Rows[0]["Product_Id"])
                                                             select var.Field<Int32?>("Quantity_Issued")).ToList();

                                    List<Int32?> receivedQty = (from var in transferProducts.AsEnumerable()
                                                                where Id.Create(var.Field<byte[]>("Product_Id")) == Id.Create(product.Rows[0]["Product_Id"])
                                                                select var.Field<Int32?>("Quantity_Received")).ToList();
                                    if (issueQty.Count() != 0 && receivedQty.Count() != 0)
                                    {
                                        if (TypeConvert.ToInt32(issueQty[0]) == TypeConvert.ToInt32(receivedQty[0]))
                                        {
                                            PivotalMessageBox.Show("Item has been fully received.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                            this.PrimaryDataRow["Product_Barcode"] = DBNull.Value;
                                            this.FormControl.GetControlByDataName("Product_Barcode").Focus();
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                        //Non-Serialized Item. Add the product directly to the grid.
                        if (IssueDocumentCheck(product, transferProducts, false))
                        {
                            AddProductToGrid(product, null, transferProducts, false);
                            //this.PrimaryDataRow["Product_Id"] = DBNull.Value;
                            productAdded = true;
                        }
                        else
                        {
                            PivotalMessageBox.Show("No Product record found for the keyed in/scanned barcode in the Issue Document.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                    }
                }
                else if (product != null && product.Rows.Count > 1)
                    PivotalMessageBox.Show("Multiple Product's found for the keyed in/scanned barcode: " +
                        TypeConvert.ToString(this.PrimaryDataRow["Product_Barcode"]) + Environment.NewLine +
                        "Please contact the Administrator.", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                else
                    PivotalMessageBox.Show("No Product record found for the keyed in/scanned barcode.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                if (productAdded)
                {
                    if (transferProducts != null && transferProducts.Rows.Count > 0)
                    {
                        IEnumerable<DataRow> query = from prods in transferProducts.AsEnumerable()
                                                     where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(product.Rows[0]["Product_Id"])
                                                         //&& Id.Create(prods.Field<byte[]>("RE_Product_Serial_No_Id")) == null
                                                     && prods.Field<bool>("Received") == false
                                                     select prods;

                        if (query != null && query.Count() > 0)
                        {
                            List<DataRow> test = query.ToList();
                            test[0]["Quantity_Received"] = TypeConvert.ToInt32(test[0]["Quantity_Received"]) + 1;
                            if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "PO Receive") ||
                                        String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "Inventory Receive"))
                            {
                                this.PrimaryDataRow["Received_Quantity"] = TypeConvert.ToInt16(this.PrimaryDataRow["Received_Quantity"]) + 1;
                            }
                            if (TypeConvert.ToInt32(test[0]["Quantity_Issued"]) == TypeConvert.ToInt32(test[0]["Quantity_Received"]))
                            {
                                test[0]["Received"] = true;
                            }
                            this.PrimaryDataRow["Received_Quantity_PerBatch"] = TypeConvert.ToInt32(this.PrimaryDataRow["Received_Quantity_PerBatch"]) + 1;
                        }

                    }
                }
                this.PrimaryDataRow["RE_Serial_Number"] = DBNull.Value;
                this.PrimaryDataRow["RE_Product_Serial_No_Id"] = DBNull.Value;
                this.PrimaryDataRow["Product_Barcode"] = DBNull.Value;
                ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Serial_Number")).ReadOnly = true;
                ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Product_Serial_No_Id")).ReadOnly = true;
                if (productAdded)
                    this.FormControl.GetControlByName("ProductBarcode").Focus();
                else
                    this.FormControl.GetControlByName("ProductBarcode").Focus();
                    //this.FormControl.GetControlByDataName("Product_Id").Focus();
                ////Check for the Products for the Updated Barcode
                //DataTable productSKU = Globals.GetDataTable(REProductSKUwithBarcodeQueryName, new object[] { this.PrimaryDataRow[ProductBarcodeFieldName] },
                //                                    new string[] { ProductIdFieldName, REProductSKUIdFieldName });

                //if (productSKU != null && productSKU.Rows.Count == 1)
                //{
                //    this.ValidateNewTransferProductAdd(productSKU.Rows[0][REProductSKUIdFieldName], productSKU.Rows[0][ProductIdFieldName], 
                //        this.PrimaryDataRow[ProductBarcodeFieldName]);
                //    this.HighlightRows();
                //}
                //else if (productSKU != null && productSKU.Rows.Count > 1)
                //    PivotalMessageBox.Show("Multiple Product SKU's found for the keyed in/scanned barcode: " +
                //        TypeConvert.ToString(this.PrimaryDataRow[ProductBarcodeFieldName]) + Environment.NewLine +
                //        "Please contact the Administrator", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //else
                //    PivotalMessageBox.Show("No Product SKU record found for the keyed in/scanned barcode.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                //this.PrimaryDataRow[ProductBarcodeFieldName] = DBNull.Value;
                //this.FormControl.GetControlByName("ProductBarcode").Focus();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Onupdate of Product SKU
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public virtual void OnUpdateReceiveProductSKU(object sender, EventArgs args)
        {
            try
            {
                if (!Convert.IsDBNull(this.PrimaryDataRow[ProductSKUIdFieldName]))
                {
                    DataTable productSKU = Globals.GetDataTable(ProductSKUswithProductSKUIdQueryName, new object[] { this.PrimaryDataRow[ProductSKUIdFieldName] },
                                                        new string[] { ProductIdFieldName, REProductSKUIdFieldName, "Barcode" });
                    if (productSKU != null && productSKU.Rows.Count == 1)
                    {
                        this.ValidateNewTransferProductAdd(productSKU.Rows[0][REProductSKUIdFieldName], productSKU.Rows[0][ProductIdFieldName],
                            productSKU.Rows[0]["Barcode"]);

                        this.HighlightRows();
                    }

                    this.PrimaryDataRow[ProductIdFieldName] = DBNull.Value;
                    this.PrimaryDataRow[ProductSKUIdFieldName] = DBNull.Value;
                    //Set the Product SKU field to read-only
                    if (this.PrimaryDataRow[ProductIdFieldName] != DBNull.Value)
                        ((PivotalForeignKey)this.FormControl.GetControlByDataName(ProductSKUIdFieldName)).ReadOnly = false;
                    else
                        ((PivotalForeignKey)this.FormControl.GetControlByDataName(ProductSKUIdFieldName)).ReadOnly = true;
                    this.FormControl.GetControlByDataName(ProductIdFieldName).Focus();
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Used to validate and add record in Transfer Product secondary
        /// Called from OnUpdateReceiveProductBarcode and OnUpdateReceiveProductSKU events.
        /// </summary>
        /// <param name="productSKUId"></param>
        /// <param name="productId"></param>
        /// <param name="skuDescriptor"></param>
        /// <param name="skuColor"></param>
        /// <param name="skuSize"></param>
        /// <param name="productBarcode"></param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.10.0     06/04/2012     NN          Initial version.
        /// </history>
        private void ValidateNewTransferProductAdd(object productSKUId, object productId, object productBarcode)
        {
            try
            {
                //DS:30102012 - Added Product Type check for not allowing Misc. Income type as per CR-VII.
                object productType = Pcm.Retail.Client.Globals.ServerSqlIndex(ProductTableName, REProductTypeFieldName, Id.Create(productId));
                if (string.Equals(TypeConvert.ToString(productType), "Miscellaneous Income"))
                {
                    //Miscellaneous Income can not be added explicitly.
                    PivotalMessageBox.Show("Miscellaneous Income can't be added explicitly.", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return;
                }

                bool createInventoryProduct = true;
                DataTable transferProducts = this.FormData.DataSet.Tables[InventoryTransferProductSegment];
                if (transferProducts != null && transferProducts.Rows.Count > 0)
                {
                    for (int i = 0; i < transferProducts.Rows.Count && (createInventoryProduct); i++)
                    {
                        if (Id.Create(transferProducts.Rows[i][ProductSKUIdFieldName]).Equals(Id.Create(productSKUId)))
                        {
                            if (!TypeConvert.ToBoolean(transferProducts.Rows[i]["GR_NewTransfer"]) &&
                                TypeConvert.ToInt16(transferProducts.Rows[i][QuantityOpenFieldName]) != 0)
                            {
                                transferProducts.Rows[i][QuantityOpenFieldName] = Convert.ToInt32(transferProducts.Rows[i][QuantityOpenFieldName]) + 1;
                                transferProducts.Rows[i][QuantityReceivedFieldName] = TypeConvert.ToInt16(transferProducts.Rows[i][QuantityReceivedFieldName]) + 1;
                                this.PrimaryDataRow["Received_Quantity"] = TypeConvert.ToInt32(this.PrimaryDataRow["Received_Quantity"]) + 1;
                                if (TypeConvert.ToInt16(transferProducts.Rows[i][QuantityOpenFieldName]) == 0)
                                    transferProducts.Rows[i][ReceivedFieldName] = true;
                                createInventoryProduct = false;
                            }
                            else if (TypeConvert.ToBoolean(transferProducts.Rows[i]["GR_NewTransfer"]))
                            {
                                transferProducts.Rows[i][QuantityOpenFieldName] = TypeConvert.ToInt16(transferProducts.Rows[i][QuantityOpenFieldName]) + 1;
                                transferProducts.Rows[i][QuantityReceivedFieldName] = TypeConvert.ToInt16(transferProducts.Rows[i][QuantityReceivedFieldName]) + 1;
                                this.PrimaryDataRow["Received_Quantity"] = TypeConvert.ToInt32(this.PrimaryDataRow["Received_Quantity"]) + 1;
                                createInventoryProduct = false;
                            }
                        }
                    }
                }

                if (createInventoryProduct)
                {
                    //Create Transfer Product secondary
                    base.NewSecondaryRecord(InventoryTransferProductSegment);
                    DataRow transferProduct = transferProducts.Rows[transferProducts.Rows.Count - 1];

                    transferProduct[QuantityIssuedFieldName] = 0;
                    transferProduct[QuantityReceivedFieldName] = 1;
                    if (this.SystemClient.SystemInformation.IsMobile)
                        transferProduct[QuantityOpenFieldName] = 0;
                    else
                        transferProduct[QuantityOpenFieldName] = 1;                    
                    transferProduct[ProductIdFieldName] = productId;
                    transferProduct[ProductSKUIdFieldName] = productSKUId;
                    transferProduct[ReceivedFieldName] = false;
                    transferProduct[FromStorageLocationIdFieldName] = PrimaryDataRow[FromStorageLocationIdFieldName];
                    transferProduct[ToStorageLocationIdFieldName] = PrimaryDataRow[ToStorageLocationIdFieldName];
                    transferProduct[ProductBarcodeFieldName] = productBarcode;
                    transferProduct["GR_NewTransfer"] = true;

                    this.PrimaryDataRow["Received_Quantity"] = TypeConvert.ToInt32(this.PrimaryDataRow["Received_Quantity"]) + 1;

                    if (this.FormView.FormName == REGoodsReceiveClientForm)
                    {
                        //Added code to highlight color for NewTransfer secondary row
                        PivotalSecondary pvtSecondary = this.FormControl.GetControlByName("RE_Inv_Transfer_Product_RE_Inventory_Transfer_Id") as PivotalSecondary;
                        if (pvtSecondary != null && pvtSecondary.Rows.Count > 0)
                            pvtSecondary.Rows[pvtSecondary.Rows.Count - 1].DefaultCellStyle.BackColor = System.Drawing.Color.YellowGreen;
                    }
                }
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc, true);
            }
        }

        /// <summary>
        /// Click of “Link to Temporary Goods Receive”
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public virtual void OnLinktoTempGRClick(object sender, EventArgs args)
        {
            try
            {
                //#region INV008

                if (this.FormView == null)
                    return;

                string errMsg = string.Empty;

                /*if (this.FormView.Dirty || this.RecordId == null || this.FormView.ValidateRequiredFields(out errMsg) == false)
                {
                    if (this.FormView.SaveRecord() == false)
                    {
                        return;
                    }
                }*/

                //Show the employee selection list
                Id linkInv = Globals.ShowSingleSelectionList("RE_Temp_Goods Receive For Pending Status To Location ?", "Pending Goods",
                    "Please select one of the items to be linked", new object[] { this.PrimaryDataRow[ToStorageLocationIdFieldName] }, new string[] { });

                //If there is no selection of employee
                if (linkInv == null)
                    return;

                DataTable invTransferProd = Globals.GetDataTable("RE All Inv Transfer Product for InvTransfer Id?",
                    new object[] { Id.Create(linkInv) }, new string[] { });

                if (invTransferProd != null && invTransferProd.Rows.Count > 0)
                {
                    for (int i = 0; i < invTransferProd.Rows.Count; i++)
                    {
                        DataTable productSKU = Globals.GetDataTable(REProductSKUwithBarcodeQueryName, new object[] { invTransferProd.Rows[i]["Product_Barcode"] },
                                                            new string[] { ProductIdFieldName, REProductSKUIdFieldName });

                        if (productSKU != null && productSKU.Rows.Count > 0)
                        {
                            this.ValidateNewTransferProductAdd(productSKU.Rows[0][REProductSKUIdFieldName], productSKU.Rows[0][ProductIdFieldName],
                                        invTransferProd.Rows[i]["Product_Barcode"]);
                            this.HighlightRows();
                        }
                    }
                }
                this.SystemClient.ExecuteServerTask("RE_Inventory_Transfer", "LinktoTempGR", new Type[] { typeof(object), typeof(object) },
                        new object[] { this.RecordId.ToByteArray(), linkInv.ToByteArray() });

                //#endregion
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Event which fires on click of the button Receive All?
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public virtual void OnClickReceiveAll(object sender, EventArgs args)
        {
            try
            {
                DataTable transferProducts = this.FormData.DataSet.Tables[InventoryTransferProductSegment];
                if (transferProducts != null && transferProducts.Rows.Count > 0)
                {
                    foreach (DataRow transferProductRow  in transferProducts.Rows)
                    {
                        allowProcessing = false;
                        ReceivedCheck(transferProductRow, true);
                    }
                }
                this.HighlightRows();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// This event fires in event of checkbox column check/uncheck for the item grid.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public virtual void OnCheckReceived(object sender, EventArgs args)
        {
            try
            {
                DataGridViewCheckBoxColumn checkbox = sender as DataGridViewCheckBoxColumn;
                int rowIndex = ((DataGridViewCellEventArgs)args).RowIndex;
                int columnIndex = ((DataGridViewCellEventArgs)args).ColumnIndex;
                bool isChecked = (Boolean)checkbox.DataGridView.Rows[rowIndex].Cells[columnIndex].FormattedValue;

                if (!allowProcessing)
                {
                    allowProcessing = true;
                    return;
                }

                allowProcessing = false;
                ReceivedCheck(this.FormData.DataSet.Tables[InventoryTransferProductSegment].Rows[rowIndex], isChecked);
                this.HighlightRows();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// This event is degigned to skip unnecessary clicks
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public virtual void OnMultipleClicks(object sender, EventArgs args)
        {
            return;
        }

        /// <summary>
        /// This Event is fired on Change of Product Id 
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.12.0    05/02/2013      AS          Initial version.
        /// </history>
        public virtual void OnUpdateRecieveProduct(object sender, EventArgs args)
        {
            try
            {
                bool productAdded = false;
                DataTable transferProducts = this.FormData.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"];
                if (this.PrimaryDataRow["Product_Id"] != DBNull.Value)
                {
                    DataTable product = Globals.GetDataTable("Product", new List<NameValuePair>() { new NameValuePair("Product_Id", 
                        this.PrimaryDataRow["Product_Id"]) });
                    if (product != null && product.Rows.Count > 0)
                    {
                        if (!TypeConvert.ToBoolean(product.Rows[0]["RE_Serialized"]))
                        {
                            if (IssueDocumentCheck(product, transferProducts, false))
                            {
                                AddProductToGrid(product, null, transferProducts,false);
                                //this.PrimaryDataRow["Product_Id"] = DBNull.Value;
                                productAdded = true;
                            }
                            //DataTable ProductuctwithoutSerialNumber = Globals.GetDataTable("RE Inv Transfer Product for Product?InvTransfer Id?",
                            // new object[] { this.PrimaryDataRow["Product_Id"], TypeConvert.ToDBValue(this.RecordId) },
                            // new string[] { });

                            //if (ProductuctwithoutSerialNumber != null && ProductuctwithoutSerialNumber.Rows.Count > 0)
                            //{
                            //    //DataTable invtransferRecBatch = this.FormData.DataSet.Tables["RE_Inv_Trnsf_Rec_Batch_Invento"];

                            //    //var count = (from prods in invtransferRecBatch.AsEnumerable()
                            //    //           where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(this.PrimaryDataRow["Product_Id"])
                            //    //           && prods.Field<bool>("Received") == false
                            //    //           select prods).Count();

                            //    //AddProductToGrid(null, productSerialNo);
                            //    this.SystemClient.ExecuteServerTask("RE_Inventory_Transfer", "updateInventoryTransferProduct", new Type[] { typeof(object), typeof(object),typeof(object) },
                            //                                                               new object[] { TypeConvert.ToDBValue(this.RecordId), this.PrimaryDataRow["Product_Id"],DBNull.Value });
                            //this.PrimaryDataRow["Product_Id"] = DBNull.Value;
                            //productAdded = true;
                            else
                            {
                                PivotalMessageBox.Show("Product was Not Found in the Issue Document or the product is already recieved", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                this.PrimaryDataRow["Product_Id"] = DBNull.Value;
                                this.FormControl.GetControlByDataName("Product_Id").Focus();
                            }
                        }
                        else
                        {
                            ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Product_Serial_No_Id")).ReadOnly = false;
                            ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Serial_Number")).ReadOnly = false;
                            this.FormControl.GetControlByDataName("RE_Serial_Number").Focus();
                            return;
                        }
                    }
                }
                if (productAdded)
                {
                    if (transferProducts != null && transferProducts.Rows.Count > 0)
                    {
                        IEnumerable<DataRow> query = from prods in transferProducts.AsEnumerable()
                                                     where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                                     //&& Id.Create(prods.Field<byte[]>("RE_Product_Serial_No_Id")) == null
                                                     && prods.Field<bool>("Received") == false
                                                     select prods;

                        if (query != null && query.Count()>0)
                        {
                            List<DataRow> test = query.ToList();
                            test[0]["Quantity_Received"] = TypeConvert.ToInt32(test[0]["Quantity_Received"]) + 1;
                            if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "PO Receive") ||
                                        String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "Inventory Receive"))
                            {
                                this.PrimaryDataRow["Received_Quantity"] = TypeConvert.ToInt16(this.PrimaryDataRow["Received_Quantity"]) + 1;
                            }
                            if (TypeConvert.ToInt32(test[0]["Quantity_Issued"]) == TypeConvert.ToInt32(test[0]["Quantity_Received"]))
                            {
                                test[0]["Received"] = true;
                            }
                            this.PrimaryDataRow["Received_Quantity_PerBatch"] = TypeConvert.ToInt32(this.PrimaryDataRow["Received_Quantity_PerBatch"]) + 1;
                        }
                    }
                }
                
                this.PrimaryDataRow["Product_Id"] = DBNull.Value;
                this.PrimaryDataRow["RE_Serial_Number"] = DBNull.Value;
                this.PrimaryDataRow["RE_Product_Serial_No_Id"] = DBNull.Value;
                this.PrimaryDataRow["Product_Barcode"] = DBNull.Value;
                ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Serial_Number")).ReadOnly = true;
                ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Product_Serial_No_Id")).ReadOnly = true;
                if (productAdded)
                    this.FormControl.GetControlByName("ProductBarcode").Focus();
                else
                    this.FormControl.GetControlByDataName("Product_Id").Focus();
                   }
            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
        }

        /// <summary>
        /// On change of Product Serial Number field 
        /// </summary>
        /// <param name="sender">PivotalControl</param>
        /// <param name="args">EventArgs</param>
        /// <history>
        /// Revision   Date        Author  Description
        /// 6.0.12.0   28/01/2013  DS      Initial Version
        /// </history>
        public virtual void OnDataSourceUpdatedRecieveSerialNumberText(PivotalControl sender, EventArgs args)
        {
            try
            {
                DataTable transferProducts = this.FormData.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"];
                DataTable transferProductsRecBatch = this.FormData.DataSet.Tables["RE_Inv_Trnsf_Rec_Batch_Invento"];
                bool productAdded = false;
                if (!Convert.IsDBNull(this.PrimaryDataRow["RE_Serial_Number"]) && !Convert.IsDBNull(this.PrimaryDataRow["Product_Id"]))
                {
                    if (transferProductsRecBatch != null)
                    {
                        if (transferProductsRecBatch.AsEnumerable().Count(a => Id.Equals(TypeConvert.ToString(a["Serial_Number"]),
                            TypeConvert.ToString(this.PrimaryDataRow["RE_Serial_Number"]).ToUpper())
                            && Id.Equals(Id.Create(a["Product_Id"]), Id.Create(this.PrimaryDataRow["Product_Id"]))) > 0)
                        {
                            PivotalMessageBox.Show("Item has been fully received.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            this.PrimaryDataRow["RE_Serial_Number"] = DBNull.Value;
                            this.FormControl.GetControlByDataName("RE_Serial_Number").Focus();
                            return;
                        }
                    }
                    if (IssueDocumentCheck(null, transferProducts, true))
                    {  
                        DataTable product = Globals.GetDataTable("Product", new List<NameValuePair>() { new NameValuePair("Product_Id", 
                        this.PrimaryDataRow["Product_Id"]) });
                        if (product != null && product.Rows.Count == 1)
                        {
                            if (TypeConvert.ToBoolean(product.Rows[0]["RE_Serialized"]))
                            {
                                AddProductToGrid(null, null, transferProducts, true);
                            }
                            else
                            {
                                AddProductToGrid(null, null, transferProducts, false);
                            }
                        }
                        //this.PrimaryDataRow["Product_Id"] = DBNull.Value;
                        productAdded = true;
                    }
                    else
                    {
                        PivotalMessageBox.Show("No product found for the selected Serial Number Or the product is already added.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                    if (productAdded)
                    {
                        IEnumerable<DataRow> query = null;
                        if (transferProducts != null && transferProducts.Rows.Count > 0)
                        {
                            if (Convert.IsDBNull(this.PrimaryDataRow["RE_Product_Serial_No_Id"]) && !Convert.IsDBNull(this.PrimaryDataRow["RE_Serial_Number"]))
                            {
                                DataTable serialNumberId = Globals.GetDataTable("RE_ProductSerialNo based on Serial_Number?Product?", new object[] { this.PrimaryDataRow["RE_Serial_Number"],
                                   this.PrimaryDataRow["Product_Id"]} , new string[] { "RE_Product_Serial_No_Id" });
                                if (serialNumberId != null && serialNumberId.Rows.Count == 1)
                                {
                                    //Id serialNumberId = Globals.SqlFind("RE_Product_Serial_No", "Serial_Number", TypeConvert.ToString(this.PrimaryDataRow["RE_Serial_Number"]));
                                    query = from prods in transferProducts.AsEnumerable()
                                            where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                            && Id.Create(prods.Field<byte[]>("RE_Product_Serial_No_Id")) == Id.Create(serialNumberId.Rows[0]["RE_Product_Serial_No_Id"])
                                            && prods.Field<bool>("Received") == false
                                            select prods;
                                }
                                else
                                {
                                    query = from prods in transferProducts.AsEnumerable()
                                            where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                            //&& Id.Create(prods.Field<byte[]>("RE_Product_Serial_No_Id")) == Id.Create(serialNumberId.Rows[0]["RE_Product_Serial_No_Id"])
                                            && prods.Field<bool>("Received") == false
                                            select prods;
                                }

                                if (query != null && query.Count() > 0)
                                {
                                    List<DataRow> test = query.ToList();
                                    test[0]["Quantity_Received"] = TypeConvert.ToInt32(test[0]["Quantity_Received"]) + 1;
                                    if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "PO Receive") ||
                                        String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "Inventory Receive"))
                                    {
                                        this.PrimaryDataRow["Received_Quantity"] = TypeConvert.ToInt16(this.PrimaryDataRow["Received_Quantity"]) + 1;
                                    }
                                    if (TypeConvert.ToInt32(test[0]["Quantity_Issued"]) == TypeConvert.ToInt32(test[0]["Quantity_Received"]))
                                    {
                                        test[0]["Received"] = true;
                                    }
                                    this.PrimaryDataRow["Received_Quantity_PerBatch"] = TypeConvert.ToInt32(this.PrimaryDataRow["Received_Quantity_PerBatch"]) + 1;
                                }
                            }
                            else
                            {
                                query = from prods in transferProducts.AsEnumerable()
                                                             where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                                             && Id.Create(prods.Field<byte[]>("RE_Product_Serial_No_Id")) == Id.Create(this.PrimaryDataRow["RE_Product_Serial_No_Id"])
                                                             && prods.Field<bool>("Received") == false
                                                             select prods;

                                if (query != null && query.Count() > 0)
                                {
                                    List<DataRow> test = query.ToList();
                                    test[0]["Quantity_Received"] = TypeConvert.ToInt32(test[0]["Quantity_Received"]) + 1;
                                    if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "PO Receive") ||
                                        String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "Inventory Receive"))
                                    {
                                        this.PrimaryDataRow["Received_Quantity"] = TypeConvert.ToInt16(this.PrimaryDataRow["Received_Quantity"]) + 1;
                                    }
                                    if (TypeConvert.ToInt32(test[0]["Quantity_Issued"]) == TypeConvert.ToInt32(test[0]["Quantity_Received"]))
                                    {
                                        test[0]["Received"] = true;
                                    }
                                    this.PrimaryDataRow["Received_Quantity_PerBatch"] = TypeConvert.ToInt32(this.PrimaryDataRow["Received_Quantity_PerBatch"]) + 1;
                                }
                            }
                        }
                    }

                    this.PrimaryDataRow["RE_Serial_Number"] = DBNull.Value;
                    this.PrimaryDataRow["RE_Product_Serial_No_Id"] = DBNull.Value;

                    if (productAdded)
                    {
                        if (transferProducts != null && transferProducts.Rows.Count > 0)
                        {
                             IEnumerable<DataRow> query = from prods in transferProducts.AsEnumerable()
                                                         where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                                         && prods.Field<bool>("Received") == false
                                                         select prods;
                             if (query != null && query.Count() > 0)
                             {
                                 this.PrimaryDataRow["RE_Serial_Number"] = DBNull.Value;
                                 this.PrimaryDataRow["RE_Product_Serial_No_Id"] = DBNull.Value;
                                 this.FormControl.GetControlByDataName("RE_Serial_Number").Focus();
                             }
                             else
                             {
                                 this.PrimaryDataRow["Product_Id"] = DBNull.Value;
                                 this.PrimaryDataRow["Product_Barcode"] = DBNull.Value;
                                 ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Serial_Number")).ReadOnly = true;
                                 ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Product_Serial_No_Id")).ReadOnly = true;
                                 this.FormControl.GetControlByName("ProductBarcode").Focus();
                             }
                        }
                    }
                    else
                    {
                        this.FormControl.GetControlByDataName("RE_Serial_Number").Focus();
                    }
                }
            }

            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
        }

        /// <summary>
        /// On change of Product Serial Number dropdown field 
        /// </summary>
        /// <param name="sender">PivotalControl</param>
        /// <param name="args">EventArgs</param>
        /// <history>
        /// Revision   Date        Author  Description
        /// 6.0.12.0   28/01/2013  DS      Initial Version
        /// </history>
        public virtual void OnDataSourceUpdatedRecieveSerialNumberDropDown(PivotalControl sender, EventArgs args)
        {
            try
            {
                DataTable transferProducts = this.FormData.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"];
                DataTable transferProductsRecBatch = this.FormData.DataSet.Tables["RE_Inv_Trnsf_Rec_Batch_Invento"];
                bool productAdded = false;
                
                if (!Convert.IsDBNull(this.PrimaryDataRow["RE_Product_Serial_No_Id"]) && !Convert.IsDBNull(this.PrimaryDataRow["Product_Id"]))
                {
                    if (transferProductsRecBatch != null)
                    {
                        //For serialized items, do not allow addition of an item which is present in the grid with same serial number and same product id.
                        if (transferProductsRecBatch.AsEnumerable().Count(a => Id.Equals(Id.Create(a["Product_Serial_No_Id"]),
                            Id.Create(this.PrimaryDataRow["RE_Product_Serial_No_Id"]))
                            && Id.Equals(Id.Create(a["Product_Id"]), Id.Create(this.PrimaryDataRow["Product_Id"]))) > 0)
                        {
                            PivotalMessageBox.Show("Item has been fully received.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            this.PrimaryDataRow["RE_Product_Serial_No_Id"] = DBNull.Value;
                            this.FormControl.GetControlByDataName("RE_Product_Serial_No_Id").Focus();
                            return;
                        }
                    }
                    if (IssueDocumentCheck(null, transferProducts, true))
                    {
                        DataTable product = Globals.GetDataTable("Product", new List<NameValuePair>() { new NameValuePair("Product_Id", 
                        this.PrimaryDataRow["Product_Id"]) });
                        if (product != null && product.Rows.Count > 0)
                        {
                            if (TypeConvert.ToBoolean(product.Rows[0]["RE_Serialized"]))
                            {
                                AddProductToGrid(null, null, transferProducts, true);
                            }
                            else
                            {
                                AddProductToGrid(null, null, transferProducts, false);
                            }
                        }
                        //this.PrimaryDataRow["Product_Id"] = DBNull.Value;
                        productAdded = true;
                    }
                    else
                    {
                        PivotalMessageBox.Show("No product found for the selected Serial Number Or the product is already added.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                    if (productAdded)
                    {
                        if (transferProducts != null && transferProducts.Rows.Count > 0)
                        {
                            IEnumerable<DataRow> query = from prods in transferProducts.AsEnumerable()
                                                         where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                                         && Id.Create(prods.Field<byte[]>("RE_Product_Serial_No_Id")) == Id.Create(this.PrimaryDataRow["RE_Product_Serial_No_Id"])
                                                         && prods.Field<bool>("Received") == false
                                                         select prods;

                            if (query != null && query.Count() > 0)
                            {
                                List<DataRow> test = query.ToList();
                                test[0]["Quantity_Received"] = TypeConvert.ToInt32(test[0]["Quantity_Received"]) + 1;
                                if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "PO Receive") ||
                                        String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "Inventory Receive"))
                                {
                                    this.PrimaryDataRow["Received_Quantity"] = TypeConvert.ToInt16(this.PrimaryDataRow["Received_Quantity"]) + 1;
                                }
                                if (TypeConvert.ToInt32(test[0]["Quantity_Issued"]) == TypeConvert.ToInt32(test[0]["Quantity_Received"]))
                                {
                                    test[0]["Received"] = true;
                                }
                                this.PrimaryDataRow["Received_Quantity_PerBatch"] = TypeConvert.ToInt32(this.PrimaryDataRow["Received_Quantity_PerBatch"]) + 1;
                            }
                            else
                            {
                                IEnumerable<DataRow> query1 = from prods in transferProducts.AsEnumerable()
                                                             where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                                             && Id.Create(prods.Field<byte[]>("RE_Product_Serial_No_Id")) == null
                                                             && prods.Field<bool>("Received") == false
                                                             select prods;

                                if (query1 != null && query1.Count() > 0)
                                {
                                    List<DataRow> test =  query1.ToList();
                                    test[0]["Quantity_Received"] = TypeConvert.ToInt32(test[0]["Quantity_Received"]) + 1;
                                    if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "PO Receive") ||
                                        String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "Inventory Receive"))
                                    {
                                        this.PrimaryDataRow["Received_Quantity"] = TypeConvert.ToInt16(this.PrimaryDataRow["Received_Quantity"]) + 1;
                                    }
                                    if (TypeConvert.ToInt32(test[0]["Quantity_Issued"]) == TypeConvert.ToInt32(test[0]["Quantity_Received"]))
                                    {
                                        test[0]["Received"] = true;
                                    }
                                    this.PrimaryDataRow["Received_Quantity_PerBatch"] = TypeConvert.ToInt32(this.PrimaryDataRow["Received_Quantity_PerBatch"]) + 1;
                                }
                            }
                        }
                    }
                    
                    this.PrimaryDataRow["RE_Serial_Number"] = DBNull.Value;
                    this.PrimaryDataRow["RE_Product_Serial_No_Id"] = DBNull.Value;
                    
                    if (productAdded)
                    {
                        if (transferProducts != null && transferProducts.Rows.Count > 0)
                        {
                            IEnumerable<DataRow> query = from prods in transferProducts.AsEnumerable()
                                                         where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                                         && prods.Field<bool>("Received") == false
                                                         select prods;
                            if (query != null && query.Count() > 0)
                            {
                                this.PrimaryDataRow["RE_Serial_Number"] = DBNull.Value;
                                this.PrimaryDataRow["RE_Product_Serial_No_Id"] = DBNull.Value;
                                this.FormControl.GetControlByDataName("RE_Product_Serial_No_Id").Focus();
                            }
                            else
                            {
                                this.PrimaryDataRow["Product_Id"] = DBNull.Value;
                                this.PrimaryDataRow["Product_Barcode"] = DBNull.Value;
                                ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Serial_Number")).ReadOnly = true;
                                ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Product_Serial_No_Id")).ReadOnly = true;
                                this.FormControl.GetControlByName("ProductBarcode").Focus();
                            }
                        }
                    }
                    else
                        this.FormControl.GetControlByDataName("RE_Product_Serial_No_Id").Focus();
                }
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc);
            }
        }

        private bool IssueDocumentCheck(DataTable product, DataTable transferProducts,bool serialized)
        {
            try
            {
                bool available = false;
                if (transferProducts!=null && transferProducts.Rows.Count>0)
                {
                    //var serializedProdsWithoutSerialNumber = from prods in transferProducts.AsEnumerable()
                    //                                         where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(this.PrimaryDataRow["Product_Id"])
                    //                                         && Id.Create(prods.Field<byte[]>("RE_Product_Serial_No_Id")) == null
                    //                                         && prods.Field<bool>("Received") == false
                    //                                         select prods;

                    if (serialized) //serialized
                    {
                        if (Convert.IsDBNull(this.PrimaryDataRow["RE_Product_Serial_No_Id"]) && !Convert.IsDBNull(this.PrimaryDataRow["RE_Serial_Number"]))
                        {
                            DataTable serialNumberId = Globals.GetDataTable("RE_ProductSerialNo based on Serial_Number?Product?", new object[] { this.PrimaryDataRow["RE_Serial_Number"],
                            this.PrimaryDataRow["Product_Id"]}, new string[] { "RE_Product_Serial_No_Id" });
                            if (serialNumberId != null && serialNumberId.Rows.Count == 1)
                            {
                                //Id serialNumberId = Globals.SqlFind("RE_Product_Serial_No", "Serial_Number", TypeConvert.ToString(this.PrimaryDataRow["RE_Serial_Number"]));
                                //if (serialNumberId != null)
                                //{
                                var temp = from prods in transferProducts.AsEnumerable()
                                           where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                           && Id.Create(prods.Field<byte[]>("RE_Product_Serial_No_Id")) == Id.Create(serialNumberId.Rows[0]["RE_Product_Serial_No_Id"])
                                           && prods.Field<bool>("Received") == false
                                           select prods;
                                if (temp != null && temp.Count() == 1)
                                {
                                    available = true;
                                }
                            }
                            else
                            {
                                var temp = from prods in transferProducts.AsEnumerable()
                                           where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                           && Id.Create(prods.Field<byte[]>("RE_Product_Serial_No_Id")) == null
                                           && prods.Field<bool>("Received") == false
                                           select prods;
                                if (temp != null && temp.Count() == 1)
                                {
                                    available = true;
                                }
                            }
                        }
                        else
                        {
                            var temp1 = from prods in transferProducts.AsEnumerable()
                                        where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                        && Id.Create(prods.Field<byte[]>("RE_Product_Serial_No_Id")) == Id.Create(this.PrimaryDataRow["RE_Product_Serial_No_Id"])
                                        && prods.Field<bool>("Received") == false
                                        select prods;
                            if (temp1 != null && temp1.Count() == 1)
                            {
                                available = true;
                            }
                            else
                            {
                                available = false;
                            }
                        }
                    }
                    else //non serialized
                    {
                        var temp = from prods in transferProducts.AsEnumerable()
                                   where Id.Create(prods.Field<byte[]>("Product_Id")) == Id.Create(product.Rows[0]["Product_Id"])
                                   && prods.Field<bool>("Received") == false
                                   select prods;
                        if (temp != null && temp.Count() == 1)
                        {
                            available = true;
                        }
                        else if (temp != null && temp.Count() > 1)
                        {
                            available = true;
                        }
                        else
                        {
                            available = false;
                        }
                        //else
                        //{
                        //    available = false;
                        //    //PivotalMessageBox.Show("Product was Not Found in the Issue Document", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //}
                    }
                }
                return available;
            }
            catch(Exception ex)
            {
               Globals.HandleException(ex);
               return false;
            }
        }

        public virtual void onCheckReceiveWithDeficit(PivotalControl sender, EventArgs args)
        {
            try
            {
                if (TypeConvert.ToBoolean(this.PrimaryDataRow["Disconn_ReceivedWithDeficit"]))
                {
                    if (PivotalMessageBox.Show("Are you sure you want to set the status to Received with Deficit?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
                        == DialogResult.OK)
                    {
                        this.PrimaryDataRow["Status"] = "Received with Deficit";
                        return;
                    }
                    else
                    {
                        this.PrimaryDataRow["Status"] = "Pending";
                        this.PrimaryDataRow["Disconn_ReceivedWithDeficit"] = false;
                        //this.FormView.Dirty = false;
                        return;
                    }
                }
                else
                {
                    this.PrimaryDataRow["Status"] = "Pending";
                    return;
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex);
            }
        }

        public virtual void Status_OnValidating(object sender, EventArgs args)
        {
            previousStatus = TypeConvert.ToString(this.PrimaryDataRow["Status"]);
        }

        public virtual void OnButtonClickPrintRMA(PivotalControl sender, EventArgs args)
        {
            try
            {
                if (this.RecordId != null)
                {
                    Globals.ShowModalReport("RE_Print RMA",RecordFilter.IndividualRecord,this.RecordId, null);
                }
            }
            catch(Exception ex)
            {
                Globals.HandleException(ex);
            }
        }

        public virtual void OnUpdateRMAStatus(PivotalControl sender, EventArgs args)
        {
            try
            {
                if (this.RecordId == null)
                {
                    if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["RMA_Status"]), "Collected") ||
                        String.Equals(TypeConvert.ToString(this.PrimaryDataRow["RMA_Status"]), "Cancelled"))
                    {
                        PivotalMessageBox.Show("You can set your status only to 'Issued'", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        this.PrimaryDataRow["RMA_Status"] = "Issued";
                        return;
                    }
                }
                else
                {
                    if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["RMA_Status"]), "Collected"))
                    {
                        this.PrimaryDataRow[ReceiveDateFieldName] = DateTime.Now;
                    }
                    else if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["RMA_Status"]), "Cancelled"))
                    {
                        this.PrimaryDataRow["Cancel_Date"] = DateTime.Now;
                    }
                }
            }
            catch(Exception ex)
            {
                Globals.HandleException(ex);
            }
        }
        #endregion
    }
}